from datetime import timedelta

from flask import render_template, request, redirect, session, jsonify, current_app

from moldels import db
from moldels.index import Commod, CommodPhotos, Users, Com_car, Comment, areas, Addrs, Orders, Buy
from utils.aliyun import send_note
from utils.common import total_price
from utils.func import get_order_id, get_note
from views import commod_blu


@commod_blu.route('/')
def index():
    # 用户昵称的显示
    user_id = session.get("user_id")

    user = db.session.query(Users).filter(Users.id == user_id).first()

    # 展示在index页面的图片数据 use = 1
    photos = db.session.query(CommodPhotos).filter(CommodPhotos.Photo_use == 1).limit(6)
    if user:
        # 显示在购物车的数据
        user.car = user.com_car.all()

    return render_template("index/index.html", photos=photos, user=user)


@commod_blu.route("/index.html")
def index1():
    return redirect("/")


# 商品详情页
@commod_blu.route("/product-details.html")
def product_details():
    # 用户昵称的显示
    user_id = session.get("user_id")

    user = db.session.query(Users).filter(Users.id == user_id).first()

    if user:
        # 显示在购物车的数据
        user.car = user.com_car.all()

    # 获取请求的参数  商品的id
    commod_id = request.args.get("commod_id")

    # 这个商品
    commod = db.session.query(Commod).filter(Commod.id == commod_id).first()

    # 这个商品所有的照片
    commod.photos = commod.commod_photos.all()

    # 相关产品

    photos = db.session.query(CommodPhotos).filter(CommodPhotos.Photo_use == 1,
                                                   CommodPhotos.commod_id != commod_id).limit(4)

    # 这个水果的评论
    comment = db.session.query(Comment).filter(Comment.com_id == commod_id).all()

    return render_template("index/product-details.html", commod=commod, user=user, photos=photos, comment=comment)


# 点击添加购物车逻辑
@commod_blu.route("/add_car")
def add_car():
    user_id = session.get("user_id")

    if not user_id:
        ret = {
            "errno": "1001",
            "errmsg": "请先登录"
        }

        return jsonify(ret)

    com_id = request.args.get("com_id")

    kg = request.args.get("kg",1)

    c = db.session.query(Com_car).filter(Com_car.user_id == user_id, Com_car.comd_id == com_id).first()

    print(c)
    # 不是初次添加
    if c:
        if kg != "undefined":
            c.comd_count += int(kg)
        else:
            c.comd_count += 1

        db.session.commit()
    else:
        # 初次添加
        com_car = Com_car(user_id=user_id, comd_id=com_id, comd_count=kg)

        db.session.add(com_car)
        db.session.commit()

    ret = {
        "errno": "0",
        "errmsg": "添加成功"

    }
    return jsonify(ret)


# 产品列表页面的显示
@commod_blu.route("/product-grid.html")
def product_grid():
    # 用户昵称的显示
    user_id = session.get("user_id")

    user = db.session.query(Users).filter(Users.id == user_id).first()

    if user:
        # 显示在购物车的数据
        user.car = user.com_car.all()

    # 要展示所有的商品图片
    show_photots = db.session.query(CommodPhotos).filter(CommodPhotos.Photo_use == 1).all()

    return render_template("index/product-grid.html", show_photots=show_photots, user=user)


# 用户主页 （可能不要）
@commod_blu.route("/user.html")
def user():
    return render_template("index/user.html")


# 购物车页面的显示
@commod_blu.route("/com_car.html")
def com_car():
    # 用户昵称的显示
    user_id = session.get("user_id")
    if not user_id:
        return redirect("/")

    user = db.session.query(Users).filter(Users.id == user_id).first()

    # 显示在购物车的数据
    user.car = user.com_car.all()

    return render_template("index/com_car.html", user=user)


# 删除购物车中的商品
@commod_blu.route("/remove_com")
def remove_com():
    rm_com_id = request.args.get("com_id")

    user_id = session.get("user_id")
    com_cc = db.session.query(Com_car).filter(Com_car.comd_id == rm_com_id, Com_car.user_id == user_id).first()

    if com_cc:
        db.session.delete(com_cc)
        db.session.commit()

        ret = {
            "errno": '0',
            "errmsg": "删除成功"
        }
    else:
        ret = {
            "errno": "011",
            "errmsg": "aaaa"
        }

    return jsonify(ret)


# 点击添加或减少商品质量的请求
@commod_blu.route("/add_sub", methods=["POST"])
def add_sub():
    user_id = session.get("user_id")

    if not user_id:
        ret = {
            "errno": 'xxx',
            "errmsg": "cccc"
        }
        return ret
    com_id = request.json.get("com_id")
    action = request.json.get("action")

    cc = db.session.query(Com_car).filter(Com_car.user_id == user_id, Com_car.comd_id == com_id).first()

    if action == "add":

        print("+++")
        cc.comd_count += 1

        db.session.commit()

        ret = {
            "errno": 0,
            "errmsg": "200"
        }

    elif action == "sub":
        print("---")
        if not cc.comd_count <= 0:
            cc.comd_count -= 1

        db.session.commit()

        ret = {
            "errno": 0,
            "errmsg": "200"
        }
    else:
        ret = {
            "errno": "122",
            "errmsg": "未知错误"
        }

    return jsonify(ret)


# 提交订单页面的显示
@commod_blu.route("/checkout.html", methods=["POST", "GET"])
def checkou():
    request_type = request.method

    user_id = session.get("user_id")
    user = db.session.query(Users).filter(Users.id == user_id).first()

    if not user:
        return redirect("/")

    # 显示在购物车的数据

    user.car = user.com_car.all()
    if request_type == "GET":

        # 显示三级联动之省的数据
        province = db.session.query(areas).filter(areas.p_id == 0).all()

        return render_template('index/checkout.html', user=user, province=province)

    else:
        # 接受参数
        name = request.json.get("name")
        call = request.json.get("call")
        phone = request.json.get("phone")
        wx = request.json.get("wx")
        p_addr = request.json.get("p_addr")
        c_addr = request.json.get("c_addr")
        a_addr = request.json.get("a_addr")
        addr = request.json.get("addr")

        comd_list = ""

        for i in user.car:
            comd_list += str(i.id)
            comd_list += ","

        try:
            # 地址添加数据库
            addr = Addrs(province=p_addr, city=c_addr, county=a_addr, definite=addr,
                         name=name, call=call, phone=phone, user_id=user_id)

            # 生成订单
            new_order = Orders(order_id=get_order_id(), user_id=user_id, comd_list=comd_list,
                               order_sum=total_price(user.car, 99), order_status="1")

            db.session.add(addr)
            db.session.add(new_order)
            db.session.commit()
        except Exception as e:
            print(e)

            ret = {
                "errno": '1112',
                "errmsg": "重新提交"
            }

        else:
            ret = {
                "errno": "0",
                "errmsg": "提交成功"
            }

            # 这里每次结算就是全部，所以直接删掉
            # 如果要删掉指定的，就要给购物车表添加id
            com_car = db.session.query(Com_car).filter(Com_car.user_id == user_id).all()
            for com in com_car:
                new_buy = Buy(com_id=com.comd_id, count=com.comd_count, order_id=new_order.id, user_id=user_id)
                # 添加已购买的数据到数据表里
                db.session.add(new_buy)
                # 删除购物车中的数据
                db.session.delete(com)
                db.session.commit()

        return jsonify(ret)


@commod_blu.route("/get_city", methods=["POST"])
def get_city():
    c_id = request.form.get("c_id")
    # 数据库查询数据

    data = db.session.query(areas).filter(areas.p_id == c_id).all()

    ret = {

    }
    for da in data:
        ret[da.c_id] = da.addr_name

    return jsonify(ret)


@commod_blu.route("/get_addr")
def get_addr():
    user_id = session.get("user_id")
    if not user_id:
        return redirect("/")

    num = request.args.get("par")

    addrs = db.session.query(Addrs).filter(Addrs.user_id == user_id).all()

    if addrs:
        if addrs[-int(num)]:
            addr = addrs[-int(num)]
        else:
            addr = addrs[0]

        ret = {
            "p_addr": addr.province,
            "c_addr": addr.city,
            "x_addr": addr.county,
            "definite": addr.definite,
            "name": addr.name,
            "call": addr.call,
            "phone": addr.phone
        }
    else:
        ret = {
            "errno": "102",
            "errmsg": "你最近没有保存地址"
        }

    return jsonify(ret)


# 订单页面
@commod_blu.route("/order.html")
def order():
    user_id = session.get("user_id")
    if not user_id:
        return redirect("/")

    user = db.session.query(Users).filter(Users.id == user_id).first()

    user.car = user.com_car.all()

    user.orders = user.orders.all()

    return render_template("index/order.html", user=user)


@commod_blu.route("/get_note_code")
def get_note_code():
    phone = request.args.get("phone")

    note = get_note()
    try:
        send_note(phone, note)
    except Exception as e:
        print(e)
        ret = {
            "errno": "0000",
            "errmsg": "发送失败",
        }

    else:
        session.permanent = True
        current_app.permanent_session_lifetime = timedelta(minutes=5)  # 设置session到期时间
        session["note_code"] = note
        ret = {
            "errno": "0",
            "errmsg": "发送成功"
        }

        print(note, "--------------")

    return jsonify(ret)
